package com.ruoyi.exam.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.exam.domain.entity.Question;
import com.ruoyi.exam.domain.vo.QuestionImportVo;
import com.ruoyi.exam.service.IQuestionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 题目，存储题目信息Controller
 * 
 * @author ruoyi
 * @date 2024-12-17
 */
@RestController
@RequestMapping("/exam/question")
public class QuestionController extends BaseController {
    @Autowired
    private IQuestionService questionService;

    /**
     * 查询题目，存储题目信息列表
     */
    @PreAuthorize("@ss.hasPermi('exam:question:list')")
    @GetMapping("/list")
    public TableDataInfo list(Question question) {
        startPage();
        List<Question> list = questionService.selectQuestionList(question);
        return getDataTable(list);
    }

    /**
     * 导出题目，存储题目信息列表
     */
    @PreAuthorize("@ss.hasPermi('exam:question:export')")
    @Log(title = "题目，存储题目信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Question question) {
        List<Question> list = questionService.selectQuestionList(question);
        ExcelUtil<Question> util = new ExcelUtil<Question>(Question.class);
        util.exportExcel(response, list, "题目，存储题目信息数据");
    }

    /**
     * 获取题目，存储题目信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('exam:question:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(questionService.selectQuestionById(id));
    }

    /**
     * 新增题目，存储题目信息
     */
    @PreAuthorize("@ss.hasPermi('exam:question:add')")
    @Log(title = "题目，存储题目信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Question question) {
        return toAjax(questionService.insertQuestion(question));
    }

    /**
     * 修改题目，存储题目信息
     */
    @PreAuthorize("@ss.hasPermi('exam:question:edit')")
    @Log(title = "题目，存储题目信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Question question) {
        return toAjax(questionService.updateQuestion(question));
    }

    /**
     * 删除题目，存储题目信息
     */
    @PreAuthorize("@ss.hasPermi('exam:question:remove')")
    @Log(title = "题目，存储题目信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(questionService.deleteQuestionByIds(ids));
    }

    @Log(title = "题目导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('exam:question:import')")
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("files") MultipartFile[] files) throws Exception {
        if (files == null || files.length == 0) {
            return AjaxResult.error("请选择要导入的文件");
        }

        try {
            // 只处理单个文件
            MultipartFile file = files[0];

            // 获取文件名（不包含后缀）作为题库
            String fileName = file.getOriginalFilename();
            String outline = fileName.substring(0, fileName.lastIndexOf("."));

            ExcelUtil<QuestionImportVo> util = new ExcelUtil<QuestionImportVo>(QuestionImportVo.class);
            List<QuestionImportVo> questionList = util.importExcel(file.getInputStream());

            // 导入数据
            String message = questionService.importQuestion(questionList, outline);

            // 如果导入成功，返回成功消息
            return AjaxResult.success(message);
        } catch (Exception e) {
            // 如果导入失败，返回错误状态和消息
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<QuestionImportVo> util = new ExcelUtil<QuestionImportVo>(QuestionImportVo.class);
        util.importTemplateExcel(response, "试题数据");
    }
}
